import React, { Component } from 'react'
import axios from 'axios'

//echarts图表
import echarts from 'echarts/lib/echarts'
import 'echarts/lib/chart/line'
import 'echarts/lib/chart/pie'

//echarts组件
import 'echarts/lib/theme/dark'
import 'echarts/lib/component/tooltip'
import 'echarts/lib/component/title'
import 'echarts/lib/component/legend'

//antd组件
import Radio from 'antd/lib/radio'
import Tabs from 'antd/lib/tabs'
import Table from 'antd/lib/table'

import styles from './scss/home.scss'
import Com from '../common/common'
import Navbar from '../Component/navbar'
import store from '../redux'
import Api from '../config/api'

const TabPane = Tabs.TabPane;
const RadioGroup = Radio.Group;

class OperBar extends Component {
    constructor(props) {
        super(props);
        this.state = {
            startDate: '',
            endDate: '',
        }
    }
    componentDidMount() {
        this.search('本月');
    }
    search(type) {
        let date = Com.computeDateGap(type);
        this.props.search(date, type);
    }
    changeDate(e) {
        this.search(e.target.value);
    }
    render() {
        const typeArr = ['本月', '上月', '近三月', '半年', '今年'];
        return (
            <div ref={(item) => { this.operbarBox = item }}>
                <Navbar>
                    <RadioGroup defaultValue={'本月'} onChange={this.changeDate.bind(this)}>
                        {typeArr.map(item => <Radio key={item} value={item}>{item}</Radio>)}
                    </RadioGroup>
                </Navbar>
            </div>
        )
    }
}

class Linechart extends Component {
    constructor(props) {
        super(props)
        this.state = {
            chartData: {
            },
            operbarHeight: 0,
            loading: false
        }
    }
    componentWillReceiveProps(nextprops) {
        let { chartData, operbarHeight, loading } = nextprops;
        this.setState({
            chartData, operbarHeight, loading
        }, () => {
            this.fullChart();
            this.runchart();
        })
    }
    componentDidMount() {
        this.unscribe = store.subscribe(this.fullChart.bind(this));
    }
    componentWillUnmount() {
        this.unscribe()
    }
    fullChart() {
        this.lineChartBox.style.height = store.getState().mainTableSize - this.state.operbarHeight - 45 - 40 + 'px';
        if (this.handleLineChart) {
            this.handleLineChart.resize();
        }
    }
    //返回echats折线图配置
    makeOption() {
        let option = {
            xAxis: {
                type: 'category',
                data: this.state.chartData.date,
                axisLabel: {
                    align: 'middle'
                },
                axisTick: {
                    alignWithLabel: true
                }
            },
            yAxis: {
                type: 'value'
            },
            title: {
                text: this.state.chartData.titleText + '短信发送结果统计',
                subtext: this.state.chartData.dateGap,
                x: 'center'
            },
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'cross'
                }
            },
            legend: {
                x: '100',
                data: ['总数', '成功', '失败', '未知']
            },
            series: [{
                name: '总数',
                data: this.state.chartData.total,
                color: '#36648B',
                type: 'line',
                smooth: true,
                animationDelay: 100
            }, {
                name: '成功',
                data: this.state.chartData.success,
                color: '#20B2AA',
                type: 'line',
                smooth: true,
                animationDelay: 300
            }, {
                name: '失败',
                data: this.state.chartData.failure,
                color: '#B22222',
                type: 'line',
                smooth: true,
                animationDelay: 500
            }, {
                name: '未知',
                data: this.state.chartData.unknownCount,
                color: '#333',
                type: 'line',
                smooth: true,
                animationDelay: 600
            }],
            animationDuration: 1200
        };
        return option
    }
    runchart() {
        let option = this.makeOption();
        if (this.handleLineChart) {
            //控制loading显隐
            this.state.loading ? this.handleLineChart.showLoading() : this.handleLineChart.hideLoading();
            this.handleLineChart.clear();
        }
        else {
            //echarts没有初始化则初始化
            this.handleLineChart = echarts.init(this.lineChartBox);
        }
        if (!this.state.loading) {
            this.handleLineChart.setOption(option);
        }
    }
    render() {
        return (
            <div className={styles["home-linechart-box"]} ref={(item) => { this.lineChartBox = item }} style={{ marginTop: '10px' }}>
            </div>
        )
    }
}

class Piechart extends Component {
    constructor(props) {
        super(props)
        this.state = {
            operbarHeight: 0,
            loading: false,
            chartData: [],
            successNum: 0,
            failureNum: 0,
            unknownCountNum: 0,
            totalNum: 0,
        }
    }
    componentWillReceiveProps(nextprops) {
        this.changeStateNum(nextprops)
    }
    componentDidMount() {
        this.changeStateNum(this.props)
        this.unscribe = store.subscribe(this.fullChart.bind(this));
    }
    componentWillUnmount() {
        this.unscribe()
    }
    fullChart() {
        this.pieChartBox.style.height = (store.getState().mainTableSize - this.state.operbarHeight - 45 - 40) * 0.7 + 'px';
        if (this.handlePieChart) {
            this.handlePieChart.resize();
        }
    }
    changeStateNum(data) {
        let successNum = 0,
            failureNum = 0,
            unknownCountNum = 0,
            totalNum = 0,
            { chartData, operbarHeight, loading } = data
        data.chartData.success.forEach((item, index) => {
            successNum += item;
            failureNum += data.chartData.failure[index];
            unknownCountNum += data.chartData.unknownCount[index];
            totalNum += data.chartData.total[index]
        })
        this.setState({
            operbarHeight,
            loading,
            chartData,
            successNum,
            failureNum,
            unknownCountNum,
            totalNum
        }, () => {
            this.fullChart();
            this.runchart();
        })
    }
    makeOption() {
        let option = {
            title: {
                text: this.state.chartData.titleText + '短信发送结果比重',
                subtext: this.state.chartData.dateGap,
                x: 'center'
            },
            legend: {
                orient: 'horizontal',
                y: 'bottom',
                data: ['成功', '失败', '未知']
            },
            series: [
                {
                    name: '比重',
                    type: 'pie',
                    radius: '55%',
                    center: ['50%', '60%'],
                    data: [
                        { value: this.state.successNum, name: '成功' },
                        { value: this.state.failureNum, name: '失败' },
                        { value: this.state.unknownCountNum, name: '未知' },
                    ],
                    itemStyle: {
                        emphasis: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }
            ],
            color: ['#3CA0FE', '#32CBCA', '#A2B5CD']
        };

        return option
    }
    runchart() {
        let option = this.makeOption();
        if (this.handlePieChart) {
            this.state.loading ? this.handlePieChart.showLoading() : this.handlePieChart.hideLoading();
        }
        else {
            this.handlePieChart = echarts.init(this.pieChartBox);
        }
        if (!this.state.loading) {
            this.handlePieChart.setOption(option);
        }
    }
    render() {
        const columns = [{
            title: '类型',
            dataIndex: 'type',
            key: 'type',
        }, {
            title: '数量',
            dataIndex: 'num',
            key: 'num',
        }];
        const tableData = [
            { key: '1', type: "总数", num: this.state.totalNum },
            { key: '2', type: '成功', num: this.state.successNum },
            { key: '3', type: '失败', num: this.state.failureNum },
            { key: '4', type: '未知', num: this.state.unknownCountNum }
        ];
        return (
            <div className={styles.piebox}>
                <div className={styles["home-piechart-box"]} ref={(item) => { this.pieChartBox = item }} style={{ marginTop: '10px' }}>
                </div>
                <div className={styles["pie-table"]}>
                    <Table pagination={false} columns={columns} dataSource={tableData} />
                </div>
            </div>
        )
    }
}

class Box extends Component {
    constructor(props) {
        super(props);
        this.state = {
            operbarHeight: 0,
            chartData: {},
            chartLoading: false,
            searchParam: { param: {}, titleText: '' },
            count: 0
        }
    }
    shouldComponentUpdate(nextprops, nextstate) {
        //判定是否是主动引起的数据变动，不是的话，不允许变动
        return nextstate.count !== this.state.count;
    }
    componentDidMount() {
        this.setState({
            operbarHeight: this.operbar.operbarBox.offsetHeight + 10 + 10
        })
    }
    setParam(param, titleText) {
        this.setState({
            param, titleText, count: this.state.count + 1
        }, () => {
            this.search();
        });
    }
    search() {
        this.setState({
            chartLoading: true,
            count: this.state.count + 1
        }, () => {
            let Stype = 'day';
            let Surl = 'querySystemDayStatistic';
            //如果是半年或者今年，调用月统计接口
            if (this.state.titleText === '半年' || this.state.titleText === '今年') {
                Stype = 'month';
                Surl = 'querySystemMonthStatistic'
            }
            axios.post(Api[Surl], { ...this.state.param, pageNum: 1, pageSize: 366 }).then((res) => {
                if (res) {
                    let list = JSON.parse(JSON.stringify(res.data.list));
                    let data = list.reverse()
                    let obj = {
                        date: [],
                        total: [],
                        success: [],
                        failure: [],
                        unknownCount: [],
                        dateGap: '',
                        titleText: ''
                    };
                    obj.dateGap = this.state.param.startTime + '到' + this.state.param.endTime;
                    obj.titleText = this.state.titleText;
                    data.forEach((item) => {
                        obj.date.push(item[Stype]);
                        obj.total.push(item.msgCount);
                        obj.success.push(item.successCount);
                        obj.failure.push(item.failureCount);
                        obj.unknownCount.push(item.unknownCount);
                    })
                    this.setState({
                        chartData: obj,
                        chartLoading: false,
                        count: this.state.count + 1
                    })
                }
            }).catch((error) => {
                console.log(error)
            })
        })
    }
    render() {
        return (
            <div>
                <OperBar ref={(item) => { this.operbar = item }} search={this.setParam.bind(this)} />
                <Tabs defaultActiveKey="1">
                    <TabPane tab="趋势" key="1">
                        <Linechart operbarHeight={this.state.operbarHeight} loading={this.state.chartLoading} chartData={this.state.chartData} />
                    </TabPane>
                    <TabPane tab="比重" key="2">
                        <Piechart operbarHeight={this.state.operbarHeight} loading={this.state.chartLoading} chartData={this.state.chartData} />
                    </TabPane>
                </Tabs>
            </div>
        )
    }
}

export default Box